import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { RoleService } from './role.service';
import { PermissionService } from '../permission/permission.service';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { User } from 'src/entities/user.entity';
import { RolesGuard } from 'src/common/guards/roles.guard';
import { Roles } from 'src/common/decorators/roles.decorator';
import { PermissionsGuard } from 'src/common/guards/permissions.guard';
import { Permissions } from 'src/common/decorators/permissions.decorator';
@Controller('roles')
export class RoleController {
  constructor(
    private readonly roleService: RoleService,
    private readonly permissionService: PermissionService,
  ) {}

  /**
   * 获取所有角色
   */
  @Get()
  async findAll() {
    const roles = await this.roleService.findAll();
    return {
      code: 200,
      message: '获取成功',
      data: roles,
    };
  }

  /**
   * 获取所有权限
   */
  @Get('permissions')
  async findAllPermissions() {
    const permissions = await this.permissionService.findAll();
    return {
      code: 200,
      message: '获取成功',
      data: permissions,
    };
  }
  /**
   * 获取当前用户的权限
   */
  @Get('my-permissions')
  async getMyPermissions(@CurrentUser() user: User) {
    const role = await this.roleService.findByName(user.role);

    return {
      code: 200,
      message: '获取成功',
      data: {
        role: user.role,
        permissions: role?.permissions.map((p) => p.name) || [],
      },
    };
  }

  /**
   * 为角色分配权限
   *
   * 只有管理员可以操作
   * 使用 @Roles 装饰器
   */
  @Post('assign-permissions')
  @UseGuards(RolesGuard)
  @Roles('admin')
  async assignPermissions(
    @Body() body: { roleId: string; permissionIds: string[] },
  ) {
    const role = await this.roleService.assignPermissions(
      body.roleId,
      body.permissionIds,
    );
    return {
      code: 200,
      message: '分配成功',
      data: role,
    };
  }
  /**
   * 创建新角色
   *
   * 使用 @Permissions 装饰器
   * 需要有 user:manage 权限
   */
  @Post()
  @UseGuards(PermissionsGuard)
  @Permissions('user:manage')
  async create(@Body() createRoleDto: any) {
    const role = await this.roleService.create(createRoleDto);

    return {
      code: 200,
      message: '创建成功',
      data: role,
    };
  }
}
